package icu.twtool.entity

import kotlin.random.Random

/**
 * 算式基
 * @param upper 可以取到得到最大值
 * @author Wen
 * @since 2022-11-01
 */
class BinaryEquationBase(
    private val upper: Int
) {

    private val upperUntilI = upper + 1
    private val upperUntilJ = upperUntilI + 1
    private val len = upper.toString().length

    /**
     * 加法：[first = i, operation = '+', second = j]                  (i + j <=  upper)
     * 减法：[first = i, operation = '-', second = (upper + 1) - j]    (i + j >   upper)
     */
    private val equations = Array(upperUntilI) { i ->
        Array(upperUntilJ) { j ->
            if (upper - j >= i) AdditionBinaryEquation(i, j, len)
            else SubtractionBinaryEquation(i, upper - j + 1, len)
        }
    }

    fun get(i: Int, j: Int): BinaryEquation? {
        return try { equations[i][j] } catch (_: Exception) { null }
    }

    fun getAdditionEquation(): BinaryEquation {
        val i = Random.nextInt(0, upperUntilI)
        val j = Random.nextInt(0, upperUntilI - i)
        return equations[i][j]
    }

    fun getSubtractionEquation(): BinaryEquation {
        val i = Random.nextInt(0, upperUntilI)
        val j = Random.nextInt(upperUntilI - i, upperUntilJ)
        return equations[i][j]
    }

    fun getEquation(): BinaryEquation {
        val i = Random.nextInt(0, upperUntilI)
        val j = Random.nextInt(0, upperUntilJ)
        return equations[i][j]
    }
}